const https = require('https');
const http = require('http');
const Stream = require('stream').Transform;

function getHttpData(url, callback) {
  const toUseModule = url.substr(0, 5) === 'https' ? https : http;

  const options = {};

  toUseModule
    .request(url, function (response) {
      if (response.statusCode !== 200) {
        return callback(new Error(`Request to ${url} failed, status code: ${response.statusCode}`));
      }

      const data = new Stream();
      response.on('data', function (chunk) {
        data.push(chunk);
      });
      response.on('end', function () {
        callback(null, data.read());
      });
      response.on('error', function (e) {
        callback(new Error(e));
      });
    })
    .end();
}

module.exports = getHttpData;
